<template>
    <div>
        <a-form ref='formRef' autocomplete='off' :model='formData' :label-col='{ span: 4 }' :wrapper-col="{ span: 18 }" @finish='submit'>
            <a-card :class='$style.nameCard' :bordered='false'>
                <a-form-item label='标题' name='name' :rules='[{required : true, message : "请填写标题"}]'>
                    <a-input v-model:value='formData.name' />
                </a-form-item>
            </a-card>
            <template v-for='(strategy, index) in formData.strategy' :key='index'>
                <a-card :class='$style.formData'>
                    <a-form-item label='股票名称'>
                        <a-input :value='shares[index].name' :bordered='false' readonly type='text' />
                    </a-form-item>
                    <a-form-item label='策略' :rules='[{required : true, message : "请选择策略"}]' :name='["strategy", index, "strategy_id"]'>
                        <a-select v-model:value='strategy.strategy_id' :options='strategys' @change='value => selectStrategy(value, index)'></a-select>
                    </a-form-item>

                    <a-form-item style="display:none" label='code' :name='["strategy", index, "code"]'>
                        <a-input type='hidden' :value='strategy.code' :bordered='false' readonly />
                    </a-form-item>
                    <a-form-item style="display:none" label='策略Id' :name='["strategy", index, "strategy_id"]'>
                        <a-input type='hidden' :value='strategy.strategy_id' :bordered='false' readonly />
                    </a-form-item>
                    
                    <a-form-item label='回测金额' :rules='[{required : true, message : "请填写回测金额"}]' :name='["strategy", index, "cash"]'>
                        <a-input v-model:value.number='strategy.cash' type='number' />
                    </a-form-item>
                    <template v-for='(field, i) in strategy.fields' :key='i'>
                        <a-form-item :label='field.name' :rules='field.rules' :name='["strategy", index, field.code]'>
                            <template v-if='field.type == 1'>
                                <a-input v-model:value='strategy[field.code]' />
                            </template>
                            <template v-else-if='field.type == 6'>
                                <XStockSelect :type='field.code_list' v-model:value='strategy[field.code]' />
                            </template>
                            <template v-else>
                                <a-select v-model:value='strategy[field.code]' :options='field.options'></a-select>
                            </template>
                        </a-form-item>
                    </template>
                </a-card>
            </template>
            <a-card :bordered='false' :class='$style.formData'>
                <a-form-item label='基准' :rules='[{required : true, message : "请选择基准"}]' name='benchmark'>
                    <a-select v-model:value='formData.benchmark' :options='BENCHMARK'></a-select>
                </a-form-item>
                <a-form-item label='起始日期' :rules='[{required : true, message : "请选择起始日期"}]' name='date'>
                    <a-range-picker valueFormat='YYYY-MM-DD' v-model:value='formData.date' />
                </a-form-item>

                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type='primary' html-type='submit' :loading='loading'>运行回测</a-button>
                </a-form-item>
            </a-card>
        </a-form>

        
    </div>
</template>

<script lang='ts' setup>
    import { strategyTradeStartApi, strategyTradeRunApi } from '@/api/strategy'
    import { reactive, ref } from '@vue/reactivity'
    import { useRoute, useRouter } from 'vue-router'
    import { BENCHMARK } from '@/constant'
    import { message } from 'ant-design-vue'
    import { strategyPageApi, strategyApi } from '@/api/strategy'
    import { batchTestRunApi } from '@/api/combinationBackTest'

    const { shares } = defineProps<{
        shares : any[]
    }>()


    const $route = useRoute()
    const $router = useRouter()

    const loading = ref(false)

    const strategys = reactive([])
    const strategyFields = new Map()

    const formData = reactive<any>({
        name : '新建组合回测',
        benchmark : '',
        date : null,
        strategy : []
    })


    shares.forEach(share => {
        let strategy:any = {
            code : share.code,
            strategy_id : '',
            start_date : '',
            end_date : '',
            cash : '',
            fields : []
        }

        formData.strategy.push(strategy)
    })

    async function selectStrategy(id, index) {
        if(!strategyFields.has(id)) {
            const res = await strategyApi({strategy_id: id, is_batch: 1})
            strategyFields.set(id, res.data.attr)
        }

        const strategy = formData.strategy[index]
        strategy.fields.splice(0)

        const attrs = strategyFields.get(id)

        attrs.forEach(attr => {
            let field:any = {
                name : attr.name,
                type : attr.type,
                code : attr.code,
                //rules : [{required : true, message : (attr.type == 1 ? '请填写' : '请选择') + attr.name}]
            }

            strategy[attr.code] = ''

            if(attr.type == 2) {
                const options = JSON.parse(attr.value)
                field.options = Object.keys(options.list).map(key => ({value : key, label : options.list[key]}))
                field.rules = [{required : options.required === 'ture', message : '请选择' + attr.name}] 
            }else if(attr.type == 6) {
                const option = JSON.parse(attr.value)
                field.code_list = option.code_list
                field.rules = [{required : option.required === 'ture', message : '请选择' + attr.name}] 
            }else {
                if(attr.value) {
                    try {
                        const option = JSON.parse(attr.value)
                        if(option) {
                            let rule:any = {
                                required : option.required === 'ture',
                                validator : (_rule, value) => {
                                    if(value === '') {
                                        if(option.required) {
                                            
                                            return Promise.reject('请填写' + attr.name);
                                        }else {
                                            return Promise.resolve()
                                        }
                                        
                                    }

                                    if(option.number) {
                                        value = Number(value)
                                        if(isNaN(value)) {
                                            return Promise.reject('请输入数字');
                                        }
                                        if('min' in option.number && value < option.number.min) {
                                            return Promise.reject(attr.name + `不能小于${option.number.min}`);
                                        }

                                        if('max' in option.number && value > option.number.max) {
                                            return Promise.reject(attr.name + `不能大于${option.number.max}`);
                                        }
                                    }

                                    return Promise.resolve()
                                }
                            }

                            field.rules = [rule]

                        }

                    } catch (error) {
                        console.log('-----------------')
                        console.log(error)
                    }
                }
            }

            strategy.fields.push(field)

        })
        
    }

    

    strategyPageApi({page: 1, nums: 10, type: 1, keyword:'', is_batch : 1}).then(data => {
        data.data.forEach(item => {
            strategys.push({
                label : item.name,
                value : item.id
            })
        })
    })


    async function submit(values) {
        let params:any = JSON.parse(JSON.stringify(values))

        params.strategy.forEach(strategy => {
            strategy.start_date = params.date[0]
            strategy.end_date = params.date[1]
        })

        delete params.date

        loading.value = true
        const res = await batchTestRunApi(params)
        loading.value = false
        if(res.success) {
            $router.push('/strategy/combinationBackTest/' + res.data.package_id)
        }else {
            message.error(res.message)
        }
    }

</script>


<style lang='scss' module>
    .nameCard {
        :global(.ant-card-body){
            padding-bottom: 0;
            padding-top: 0;
        }

        :global(.ant-form-item){
             margin-bottom: 0 !important;
        }
    }
    .form{
        width: 600px;
        margin: auto;
    }

    .formData{
        margin-top: 20px;
        &:first-child{
            margin-top: 0;
        }

        :global(.ant-form-item){
            &:last-child{
                margin-bottom: 0 !important;
            }
        }
    }

</style>